<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar v-if="!getQuery.folderId">
        <a-button
          type="button"
          @click="handleFolderForm({ parentCode: folderId, groupType })"
          v-auth="'filemanager:filemanager:edit'"
        >
          <Icon icon="fluent:add-12-filled" /> {{ t('新增文件夹') }}
        </a-button>
        <UploadForm :folderId="folderId" :groupType="groupType" @success="handleSuccess" />
        <Popconfirm
          :title="t('是否确认选中的文件吗？')"
          @confirm="handleDelete({ ids: getSelectRowKeys().join(',') })"
        >
          <a-button type="button" v-auth="'filemanager:filemanager:edit'">
            <Icon icon="ant-design:delete-outlined" /> {{ t('删除') }}
          </a-button>
        </Popconfirm>
        <a-button
          type="button"
          @click="handleMoveForm({ folderId, groupType, ids: getSelectRowKeys().join(',') })"
          v-auth="'filemanager:filemanager:edit'"
        >
          <Icon icon="ant-design:swap-outlined" /> {{ t('移动文件') }}
        </a-button>
        <a-button
          type="button"
          @click="handleSharedForm({ folderId, groupType, ids: getSelectRowKeys().join(',') })"
          v-auth="'filemanager:filemanager:edit'"
        >
          <Icon icon="ant-design:share-alt-outlined" /> {{ t('分享文件') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <div v-if="record.fileType == 'folder'">
          <Icon icon="fa fa-folder-o" /> &nbsp;
          <a @click="handleGoFolder({ id: record.folderId })">
            {{ record.fileName }}
          </a>
        </div>
        <div v-else>
          <Icon icon="fa fa-file-text-o" /> &nbsp;
          <a @click="handlePreview({ id: record.fileUploadId })">
            {{ record.fileName }}
          </a>
        </div>
      </template>
      <template #summary>
        <Table.Summary :fixed="'top'">
          <Table.Summary.Row v-show="folderId != '0' && folderId != getQuery.folderId">
            <Table.Summary.Cell
              :index="0"
              class="text-center cursor-pointer"
              @click="handleGoFolder()"
            >
              <div>#</div>
            </Table.Summary.Cell>
            <Table.Summary.Cell
              :index="1"
              class="text-center cursor-pointer"
              @click="handleGoFolder()"
            >
              <Icon icon="icon-action-undo" />
            </Table.Summary.Cell>
            <Table.Summary.Cell
              :index="2"
              class="cursor-pointer"
              style="border-right: 0"
              :col-span="5"
              @click="handleGoFolder()"
            >
              <Icon icon="fa fa-folder-o" /> &nbsp;...
            </Table.Summary.Cell>
            <Table.Summary.Cell style="border-right: 0" />
          </Table.Summary.Row>
        </Table.Summary>
      </template>
    </BasicTable>
    <FolderForm @register="registerFolderModal" @success="handleSuccess" />
    <MoveForm @register="registerMoveModal" @success="handleSuccess" />
    <SharedForm @register="registerSharedModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsFilemanagerList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, unref, watch } from 'vue';
  import { Table, Popconfirm } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { filemanagerDelete, filemanagerListData } from '/@/api/filemanager/filemanager';
  import { filemanagerFolderDelete } from '/@/api/filemanager/filemanagerFolder';
  import { useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import FolderForm from './form/folder.vue';
  import UploadForm from './form/upload.vue';
  import MoveForm from './form/move.vue';
  import SharedForm from './form/shared.vue';
  import { useQuery } from '/@/hooks/web/usePage';

  const { t } = useI18n('filemanager');
  const { showMessage } = useMessage();
  const { ctxAdminPath } = useGlobSetting();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'icon-docs',
    value: router.currentRoute.value.meta.title || t('文件管理'),
  };
  const getQuery = useQuery();
  const folderId = ref<string>(getQuery.value.folderId);
  const groupType = ref<string>('global');

  const props = defineProps({
    treeCode: String,
    groupType: String,
  });

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('文件名称'),
        field: 'fileName',
        component: 'Input',
      },
      {
        label: t('上传者'),
        field: 'createBy',
        fieldLabel: 'createByName',
        component: 'ListSelect',
        componentProps: {
          selectType: 'empUserSelect',
        },
      },
      {
        label: t('上传时间'),
        field: 'dateRange',
        component: 'RangePicker',
        componentProps: {},
      },
    ],
    fieldMapToTime: [['dateRange', ['createDate_gte', 'createDate_lte']]],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('名称'),
      dataIndex: 'fileName',
      key: 'a.file_name',
      sorter: true,
      width: 300,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('文件类型'),
      dataIndex: 'fileType',
      key: 'a.file_type',
      format: (text: string) => {
        return { image: t('图片'), media: t('媒体'), file: t('文档') }[text] ?? '';
      },
      sorter: true,
      width: 90,
      align: 'center',
    },
    {
      title: t('文件大小'),
      dataIndex: 'fileSizeFormat',
      sorter: false,
      width: 130,
      align: 'center',
    },
    {
      title: t('上传者'),
      dataIndex: 'createByName',
      key: 'a.create_by',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('上传时间'),
      dataIndex: 'createDate',
      key: 'a.create_date',
      sorter: true,
      width: 130,
      align: 'center',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑文件夹'),
        onClick: handleFolderForm.bind(this, { id: record.folderId }),
        auth: 'filemanager:filemanager:edit',
        ifShow: () => record.fileType == 'folder',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除文件夹'),
        popConfirm: {
          title: t('是否确认删除文件夹'),
          confirm: handleFolderDelete.bind(this, { id: record.folderId }),
        },
        auth: 'filemanager:filemanager:edit',
        ifShow: () => record.fileType === 'folder',
      },
      {
        icon: 'ant-design:download-outlined',
        title: t('下载文件'),
        onClick: handleDownload.bind(this, { id: record.fileUploadId }),
        auth: 'filemanager:filemanager:edit',
        ifShow: () => record.fileType !== 'folder',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除文件'),
        popConfirm: {
          title: t('是否确认删除文件'),
          confirm: handleDelete.bind(this, { ids: record.id }),
        },
        auth: 'filemanager:filemanager:edit',
        ifShow: () => record.fileType !== 'folder',
      },
    ],
  };

  const [registerFolderModal, folderAction] = useModal();
  const [registerMoveModal, moveAction] = useModal();
  const [registerSharedModal, sharedAction] = useModal();
  const [registerTable, { reload, getRawDataSource, getSelectRowKeys }] = useTable({
    api: filemanagerListData,
    beforeFetch: (params) => {
      params.folderId = folderId.value;
      params.groupType = groupType.value;
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    clickToRowSelect: false,
    rowSelection: {
      type: 'checkbox',
    },
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
  });

  watch(
    () => props.treeCode,
    async () => {
      folderId.value = props.treeCode || '';
      reload();
    },
  );

  watch(
    () => props.groupType,
    async (value, oldValue) => {
      if (value == 'global' && oldValue == '') return;
      groupType.value = props.groupType || '';
      reload();
    },
  );

  function handleGoFolder(record?: Recordable) {
    if (!record) {
      const { otherData } = unref(getRawDataSource());
      record = { id: otherData?.folder?.parentCode };
    }
    folderId.value = record.id || '0';
    reload();
  }

  function handleFolderForm(record?: Recordable) {
    folderAction.openModal(true, record);
  }

  async function handleFolderDelete(record: Recordable) {
    const res = await filemanagerFolderDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  const preview = import.meta.env.VITE_FILE_PREVIEW || 'true';

  function handlePreview(record: Recordable) {
    const url = ctxAdminPath + '/file/download/' + record.id + '?preview=' + preview;
    let layerWidth = $(window).width();
    if (layerWidth < 800) {
      layerWidth -= 15 * 2;
    } else {
      layerWidth -= 100 * 2;
    }
    let layerHeight = $(window).height();
    if (layerHeight < 500) {
      layerHeight -= 15 * 2;
    } else {
      layerHeight -= 25 * 2;
    }
    window.layer.open({
      type: 2,
      maxmin: true,
      shadeClose: false, // 点击背景关闭
      title: false,
      area: [layerWidth + 'px', layerHeight + 'px'],
      method: 'get',
      content: url,
    });
  }

  async function handleDownload(record: Recordable) {
    downloadByUrl({ url: ctxAdminPath + '/file/download/' + record.id });
  }

  async function handleDelete(record: Recordable) {
    if (!record.ids || record.ids == '') {
      showMessage(t('请选中要删除的文件或文件夹'));
      return;
    }
    const res = await filemanagerDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  function handleMoveForm(record: Recordable) {
    if (!record.ids || record.ids == '') {
      showMessage(t('请选中要移动的文件或文件夹'));
      return;
    }
    moveAction.openModal(true, record);
  }

  function handleSharedForm(record: Recordable) {
    if (!record.ids || record.ids == '') {
      showMessage(t('请选中要分享的文件或文件夹'));
      return;
    }
    sharedAction.openModal(true, record);
  }

  function handleSuccess() {
    reload();
  }
</script>
